package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * ClassName: JwtUtil
 * Package: com.atguigu.lease.common.utils
 * Description:
 * JwtUtil : jwt工具类，用于生成和解析token，
 * 其中tokenExpiration是token的过期时间，单位是毫秒，
 * tokenSignKey是用于生成token的密钥，SignatureAlgorithm.HS512是用于生成token的算法，
 * 可以通过调用Keys.hmacShaKeyFor方法来生成。
 *
 * @Autor: xvyy
 * @Create: 2024/11/20 - 20:28
 * @Version: v1.0
 */
public class JwtUtil {

    //todo token过期时间
    private static final long tokenExpiration = 60 * 60 * 1000L;
    private static final SecretKey tokenSignKey = Keys.hmacShaKeyFor("M3sKKI6pYGVavfDZw90a0lTpGYX1d4AQ".getBytes());

    /**
     * 创建token
     *
     * @param userId
     * @param username
     * @return
     */
    public static String createToken(Long userId, String username) {
        String token = Jwts.builder().
                setSubject("LOGIN_USER").
                setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)).
                claim("userId", userId).
                claim("username", username).
                signWith(tokenSignKey).
                compressWith(CompressionCodecs.GZIP).
                compact();
        return token;
    }

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        if (token == null) {
            //todo  抛出异常 : 未登录
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
            //todo 解析token
            Jws<Claims> claimsJws = Jwts.parserBuilder().
                    setSigningKey(tokenSignKey).
                    build().parseClaimsJws(token);
            return claimsJws.getBody();

        } catch (ExpiredJwtException e) {
            //todo  抛出异常 : token过期
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            //todo  抛出异常 : token非法
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
}
